package com.pascal91.webpp.controller;

import com.pascal91.webpp.model.Users;
import com.pascal91.webpp.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    UsersService usersService;

    @RequestMapping(value = "/login/", method = RequestMethod.POST)
    public ModelAndView login(HttpSession httpSession, Model model,
                              @RequestParam(value = "login", required = true) String login,
                              @RequestParam(value = "password", required = true) String password){

        ModelAndView view = new ModelAndView("redirect:/home.html");
        Users user = usersService.findUserByLogin(login);

        if (user != null){
            user.getPassword().equals(password);
            httpSession.setAttribute("user", user);
//            view = new ModelAndView("redirect:/home.html");
        }

//        else{
//            view = new ModelAndView("home");
//            model.addAttribute("error", "Ошибка входа.");
//            model.addAttribute("user", new Users());
//        }
        return view;
    }

    @RequestMapping("/logout/")
    public ModelAndView logout(HttpSession httpSession){
        httpSession.setAttribute("user", null);
        return new ModelAndView("redirect:/home.html");
    }

}
